package com.fgbf.todo.Managers;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.fgbf.todo.Data.DB.DBHelper;
import com.fgbf.todo.Data.SharedData.SharedData;
import com.fgbf.todo.MainClasses.User;

public class LoginManager {
	
	////////////////////////////////////////////////////////////////////////////////////////
	// INSTANCE DATA
	////////////////////////////////////////////////////////////////////////////////////////
	
	private Context context;
	private DBHelper dbHelper;
	private SQLiteDatabase database;
	
	
	////////////////////////////////////////////////////////////////////////////////////////
	// CONSTRUCTORS
	////////////////////////////////////////////////////////////////////////////////////////
	
	/**
	 * Constructs a new LoginManager with the given Activity context
	 * @param context The current context
	 */
	public LoginManager(Context context) {
		this.context = context;
	}
	
	////////////////////////////////////////////////////////////////////////////////////////
	// PUBLIC METHODS
	////////////////////////////////////////////////////////////////////////////////////////
	
	/**
	 * Adds a user to the database
	 * @param A valid instantiated User
	 * @return A boolean representing whether or not the user was added successfully
	 */
	public boolean addUserToDB(User user) {
		boolean userAdded = true;
		try{
			this.openDB();
			createEntry(user.getUsername(), user.getPassword());
			this.closeDB();
		}
		catch (Exception e) {
			userAdded = false;
			e.printStackTrace();
		}
		return userAdded;
	}
	//--------------------------------------------------------------------------------------


	/**
	 * Prints out the values in the database into logcat
	 */
	public void dumpUserDB() {
		this.openDB();
		String str = this.getData();
		this.closeDB();
		Log.v("TABLE", "" + str);
	}
	//--------------------------------------------------------------------------------------
	
	/**
	 * Checks to see if the given username exists and if the given password matches the user's password
	 * @param user The given username
	 * @param password The given password
	 * @return boolean value representing whether or not the username was found and the password was matched
	 */
	public boolean checkLogin(String user, String password){
		
		boolean userExists = false;
		boolean passCorrect = false;
		User currUser;
		
		try{
			this.openDB();
			
			String[] cols = new String[]{DBHelper.KEY_ROWID, DBHelper.KEY_USERNAME, DBHelper.KEY_PASSWORD};
			Cursor c = database.query(DBHelper.DB_USER_TABLE, cols, null, null, null, null, null);
			
			int iUserName = c.getColumnIndex(DBHelper.KEY_USERNAME);
			int iPassWord = c.getColumnIndex(DBHelper.KEY_PASSWORD);
			
			for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
				currUser = new User(c.getString(iUserName), c.getString(iPassWord));
				
				if (currUser.getUsername().equals(user)){
					userExists = true;
					if(currUser.getPassword().equals(password)) {
						passCorrect = true;
					}
				}
			}
			
			this.closeDB();
		}
		
		catch(Exception e){
			e.printStackTrace();
		}
		
		return (userExists && passCorrect);
	}
	//--------------------------------------------------------------------------------------
	
	/**
	 * Method checks a given username to see if it already exists in the Database
	 * @param user The given username
	 * @return Boolean value, true if the username name doesn't already exist in the database, false otherwise
	 */
	public boolean userNameExists(String user){
		
		User currUser;
		boolean userNameExists = false;
		
		try{
			this.openDB();
			
			String[] cols = new String[]{DBHelper.KEY_ROWID, DBHelper.KEY_USERNAME, DBHelper.KEY_PASSWORD};
			Cursor c = database.query(DBHelper.DB_USER_TABLE, cols, null, null, null, null, null);
			
			int iUserName = c.getColumnIndex(DBHelper.KEY_USERNAME);
			int iPassWord = c.getColumnIndex(DBHelper.KEY_PASSWORD);
			
			for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
				currUser = new User(c.getString(iUserName), c.getString(iPassWord));
				if (currUser.getUsername().equals(user)) 
					userNameExists = true;
			}
			
			this.closeDB();
		}
		
		catch(Exception e){
			e.printStackTrace();
		}
		
		return userNameExists;
	}
	//--------------------------------------------------------------------------------------
	
	/**
	 * Updates the current user that is "logged in", uses SharedPreferences inside of 
	 * the SharedData class
	 * @param user The name of the newly logged in user
	 * @param act The current activity
	 */
	public void updateLoginData(String user, Boolean stayLoggedIn, Activity act) {
		SharedData.putString(act, SharedData.KEY_LOGGED_IN, user);
		SharedData.putBoolean(act, SharedData.KEY_STAY_LOGGED_IN, stayLoggedIn);
	}
	//--------------------------------------------------------------------------------------
	
	/**
	 * Updates the current user that is "logged in", uses SharedPreferences inside of 
	 * the SharedData class
	 * @param user The name of the newly logged in user
	 * @param act The current activity
	 */
	public void updateLoginData(Boolean stayLoggedIn, Activity act) {
		SharedData.putBoolean(act, SharedData.KEY_STAY_LOGGED_IN, stayLoggedIn);
	}
	//--------------------------------------------------------------------------------------
	
	public String getLoggedInUsername(Activity act) {
		return SharedData.getString(act, SharedData.KEY_LOGGED_IN);
	}
	//--------------------------------------------------------------------------------------
	
	public boolean checkStayLoggedIn(Activity act) {
		return SharedData.getBoolean(act, SharedData.KEY_STAY_LOGGED_IN);
	}

	
	////////////////////////////////////////////////////////////////////////////////////////
	// PRIVATE METHODS
	////////////////////////////////////////////////////////////////////////////////////////
	
	/**
	 * Uses the DBHelper to open the database
	 * @return The current instance of LoginManager
	 */
	private LoginManager openDB() {
		dbHelper = new DBHelper(context);
		database = dbHelper.getWritableDatabase();
		return this;
	}
	//--------------------------------------------------------------------------------------

	/**
	 * Uses the DBHelper to close the database
	 */
	private void closeDB() {
		dbHelper.close();
	}
	//--------------------------------------------------------------------------------------
	
	/**
	 * Creates an username/password entry in the database
	 * Must open the database prior to calling and close the database after calling
	 * @param userName The desired username to be entered in the database
	 * @param passWord The desire password to be entered in the database
	 * @return The rowId of the newly entered rowa
	 */
	private long createEntry(String userName, String passWord) {
		ContentValues cv = new ContentValues();
		cv.put(DBHelper.KEY_USERNAME, userName);
		cv.put(DBHelper.KEY_PASSWORD, passWord);
		return database.insert(DBHelper.DB_USER_TABLE, null, cv);
	}
	//--------------------------------------------------------------------------------------
	

	/**
	 * Returns string of data
	 * Need to open/close database before/after calling
	 * @return A String representation of all the username and passwords in the database
	 */
	private String getData() {
		String[] cols = new String[]{DBHelper.KEY_ROWID, DBHelper.KEY_USERNAME, DBHelper.KEY_PASSWORD};
		Cursor c = database.query(DBHelper.DB_USER_TABLE, cols, null, null, null, null, null);
		
		String result = "";
		
		int iRow = c.getColumnIndex(DBHelper.KEY_ROWID);
		int iUserName = c.getColumnIndex(DBHelper.KEY_USERNAME);
		int iPassWord = c.getColumnIndex(DBHelper.KEY_PASSWORD);
		
		for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
			result = result + c.getString(iRow) + " " + c.getString(iUserName) + " " + c.getString(iPassWord) + "\n";
		}
		
		return result;
	}
	//--------------------------------------------------------------------------------------

	/**
	 * Fetches a username when given the correct rowId for the database
	 * Need to open/close database before/after calling
	 * @param l A rowId
	 * @return The username that corresponds to the given rowId
	 */
	private String getUserName(long l) {
		String[] cols = new String[]{DBHelper.KEY_ROWID, DBHelper.KEY_USERNAME};
		Cursor c = database.query(DBHelper.DB_USER_TABLE, cols, DBHelper.KEY_ROWID+"-" + l, null, null, null, null);
		
		int iUserName = c.getColumnIndex(DBHelper.KEY_USERNAME);
		
		if(c != null) {
			c.moveToFirst();
			String username = c.getString(iUserName);
			return username;
		}
		return "";
	}
	//--------------------------------------------------------------------------------------



}
